/*
 *  Copyright 2013 Utkin Dmitry
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#include <QDebug>
#include <QVariant>
#include <QSqlQuery>
#include <QSqlError>
#include "Settings.h"
#include "LocationDb.h"

namespace protoqtrpc
{
namespace location
{

LocationDb::LocationDb()
{
    if (!QSqlDatabase::isDriverAvailable("QSQLITE"))
        qFatal("Qt is not compiled with sqlite support");

    QSettings& settings = Settings::settings();
    const QString& dbPath = settings.value("db/path", "location_service.sqlite").toString();

    mDb = QSqlDatabase::addDatabase("QSQLITE", "LocationDB");
    mDb.setDatabaseName(dbPath);

    if (!mDb.open())
        qFatal("Failed to open db %s: %s", mDb.databaseName().toUtf8().constData(),
               mDb.lastError().text().toUtf8().constData());

    QSqlQuery query(mDb);
    if (!query.exec("PRAGMA encoding = \"UTF-8\""))
        qWarning() << "DB: failed to set encoding utf-8";
    if (!query.exec("PRAGMA foreign_keys = ON"))
        qWarning() << "DB: failed to enable foreign keys";
}

LocationDb::~LocationDb()
{
    if (mDb.isOpen())
        mDb.close();
}

LocationDb& LocationDb::inst()
{
    static LocationDb instance;
    return instance;
}

QSqlDatabase& LocationDb::db()
{
    return mDb;
}

}
}
